<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed'); //seguridad bloqueo de carpetas

class Users extends CI_Controller{

    function __construct() {
        parent::__construct();
        $this->load->model('Users_Model');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->library('email');
        
        
    }

 
       

    function login() {

       
        
    
     $data['title'] = 'Login Usuario';
        $data['main_content'] = 'users/login';
        $this->load->view('includes/template', $data);
    


        }
    function logout(){
        
      $this->session->sess_destroy();
      redirect('dashboard');
    }

    function register() {
        $data['title'] = 'Crear nueva cuenta';
        $data['main_content'] = 'users/register';
        $this->load->view('includes/template', $data);
    }
    

    function retry_password() {
        
    }
     
        

//    function verify_login() {               //verificar login
//             
//
// $this->form_validation->set_rules('username', 'Nombre de usuario', 'trim|required|callback__username_check');
//         $this->form_validation->set_rules('usernamelogin', 'Nombre de usuario', 'trim|required'); //trim sacar espacios- str-- pasar a mayusculas
//         $this->form_validation->set_message('required', 'El campo %s es Requerido');
//       
//       
//         
//        if ($this->form_validation->run() == FALSE) {
//           $this->index();
//            
//        } else {
//        
//        
//        $username = $this->input->post('username');
//        $password = md5($this->input->post('password'));
//        $login = $this->Users_Model->verify_login($username,$password);
//      
//           
//       
//           
//       
//            $data = array(
//                'is_logued_in' => TRUE,
//                'nombre_usuario' => $login[0]->username,
//                'name' => $login[0]->name,
//                'user_id' => $login[0]->id,
//                'mail' =>$login[0] ->email   
//                 ); 
//             
//            $this->session->set_userdata($data);
//            redirect('dashboard');
//      
//        }
//    }
    

    function create_account() {

        $this->form_validation->set_rules('name', 'Nombre', 'trim|required');
        $this->form_validation->set_rules('username', 'Nombre de usuario', 'trim|required|callback__username_check'); //trim sacar espacios- str-- pasar a mayusculas
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__email_check');
        $this->form_validation->set_rules('password', 'Contraseña', 'trim|required|md5');
        $this->form_validation->set_rules('re_password', 'confirmacion de clave', 'trim|required|matches[password]|md5|');
        $this->form_validation->set_message('required', 'El campo %s es Requerido');
        $this->form_validation->set_message('valid_email', 'El Campo %s no es valido');
        $this->form_validation->set_message('_username_check', 'El %s ya existe');
        $this->form_validation->set_message('_email_check', 'El %s ya existe');
        $this->form_validation->set_message('matches', 'Las contraseñas no coinciden');

        if ($this->form_validation->run() == FALSE) {
            $this->register();
        } else {
            $name = $this->input->post('name');
            $username = $this->input->post('username');
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $activation_code = $this->_random_string(10);                 //$this->_random_string(10);
            $insert = $this->Users_Model->insert_user($name, $username, $email, $password, $activation_code);

 
//Email confirmacion

          

              $this->email->from('soporte@ecommers.com,trabajosap');
              $this->email->to($email);
              $this->email->subject('verificacion de registro ecommers');
              $this->email->message('Por favor verifique su registro' . anchor('http://localhost/ci/users/register_confirm/' . $activation_code, 'Valide su correo'));
              $this->email->send();
              
              $this->register_ok();
              
              }
              }
              
               function register_ok() {

        $data['title'] = 'registro_completado';
        $data['main_content'] = 'users/register_ok';
        $this->load->view('includes/template', $data);
    }

              function register_confirm($activation_code = '') {           //comprueba codigo de activacion con la base se datos
              if ($activation_code == '') {
              die('Codigo de verificacion Errado');
              } else {
              $update = $this->Users_Model->confirm_registration($activation_code);
              if ($update) {
              echo 'Registro Completado';
              redirect('dashboard');
              } else {
              echo 'su verificacion de registro fallo';
              }
        }
    }

    function _username_check($username) {                        //comprueba si existe ya el usuario
        return $this->Users_Model->username_check($username);
    }

    function _email_check($email) {                           //guion adelante function es un metodo privado
        return $this->Users_Model->email_check($email);
    }

     function _random_string($length) {                      //crea un codigo de activacion
      $base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';
      $max = strlen($base) - 1;
      $activation_code = '';
      while (strlen($activation_code) < $length)
      $activation_code .= $base{mt_rand(0, $max)};
      return $activation_code;
      }
   
}

?>
